package com.senseuni.da.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.NetworkInfo
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import com.elvishew.xlog.XLog
import com.jeremyliao.liveeventbus.LiveEventBus
import com.senseuni.da.events.MyEvent
import com.senseuni.da.events.NetworkStateChangedEvent

class WifiBroadcast : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent) {
        val action = intent.action
        if (WifiManager.EXTRA_WIFI_STATE == action) {
            val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)
            LiveEventBus.get<Any>(MyEvent.KEY_WIFI_STATE_CHANGED).post(wifiState)
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION == action) {
            val networkInfo: NetworkInfo? = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)
            val wifiInfo: WifiInfo? = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO)
            networkInfo?.let {
                val state = it.state
                XLog.d("network state changed: $state")
                val event = NetworkStateChangedEvent(state, wifiInfo)
                LiveEventBus.get<NetworkStateChangedEvent>(MyEvent.KEY_NETWORK_STATE_CHANGED).post(event)
            }
        }

    }


}